package com.masterclient.app.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.App;
import com.masterclient.app.MainActivity;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.businessmodule.minemodule.index.PersonalFragment;
import com.masterclient.app.businessmodule.minemodule.point.PointActivity;
import com.masterclient.app.businessmodule.minemodule.point.PointProductsActivity;
import com.masterclient.app.businessmodule.minemodule.redpack.RedPackedActivity;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.businessmodule.vipmodule.activity.InComeActivity;
import com.masterclient.app.businessmodule.vipmodule.activity.PromotionProfitActivity;
import com.masterclient.app.businessmodule.vipmodule.activity.SaleOrderDetailActivity;
import com.masterclient.app.businessmodule.vipmodule.fragment.VipCenterFragment;
import com.masterclient.app.modules.aftersale.LogistInfoActivity;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.category.CategoryDetailActivity;
import com.masterclient.app.modules.chezhubang.CzbWebActivity;
import com.masterclient.app.modules.coupon.CouponActivity;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;
import com.masterclient.app.modules.order.CustomerOrderActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by FuZhi on 2017/8/22.
 */

public class CommonUtil {

    /**
     * 返回YYYYMMDD日期字符串
     *
     * @param year
     * @return
     */
    public static String getDateStr(int year, int month, int day) {
        String year_str = String.valueOf(year);
        String month_str = String.valueOf(month + 1);
        String day_str = String.valueOf(day);
        if (month_str.length() < 2)
            month_str = "0" + month_str;
        if (day_str.length() < 2)
            day_str = "0" + day_str;
        return year_str + month_str + day_str;
    }

    /**
     * 转换成整形
     **/
    public static int conversionInt(double d) {
        int i = (int) (d + 0.5);
        return i;
    }

    /**
     * 保留double类型小数后两位，不四舍五入，直接取小数后两位 比如：10.1269 返回：10.12
     *
     * @param doubleValue
     * @return
     */
    public static String d2(double doubleValue) {
        // 保留4位小数
        DecimalFormat df = new DecimalFormat("#.0000");
        String result = df.format(doubleValue);

        // 截取第一位
        String index = result.substring(0, 1);

        if (".".equals(index)) {
            result = "0" + result;
        }

        // 获取小数 . 号第一次出现的位置
        int inde = firstIndexOf(result, ".");

        // 字符串截断
        return result.substring(0, inde + 3);
    }

    public static String numberFormat(String content, boolean isShowW) {
        int totalIntLength = (((long) Double.parseDouble(content)) + "").length();
        if (totalIntLength < 6 || (!isShowW && totalIntLength < 9)) {
            return content;
        } else if (totalIntLength < 9) {
            return content.substring(0, totalIntLength - 4) + "W+";
        } else {
            return content.substring(0, totalIntLength - 8) + "亿+";
        }
    }


    /**
     * 查找字符串pattern在str中第一次出现的位置
     *
     * @param str
     * @param pattern
     * @return
     */
    public static int firstIndexOf(String str, String pattern) {
        for (int i = 0; i < (str.length() - pattern.length()); i++) {
            int j = 0;
            while (j < pattern.length()) {
                if (str.charAt(i + j) != pattern.charAt(j))
                    break;
                j++;
            }
            if (j == pattern.length())
                return i;
        }
        return -1;
    }

    /**
     * dp转换为px
     */
    public static int dpToPx(Context context, float adius) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (adius * density);
    }

    /**
     * 通过反射修改TabLayout的Indicator宽度
     */
    public static void setUpIndicatorWidth(TabLayout tabLayout, int marginLeft, int marginRight) {
        Class<?> tabLayoutClass = tabLayout.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayoutClass.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        LinearLayout layout = null;
        try {
            if (tabStrip != null) {
                layout = (LinearLayout) tabStrip.get(tabLayout);
            }
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    params.setMarginStart(dpToPx(App.context, marginLeft));
                    params.setMarginEnd(dpToPx(App.context, marginRight));
                }
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static boolean isOk(String str) {
        return Pattern.compile("^[0-9a-zA-Z]{1,13}$").matcher(str).matches();
    }

    //此方法只是关闭软键盘 可以在finish之前调用一下
    public static void hintKbTwo(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && context.getCurrentFocus() != null) {
            if (context.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    //把View转换成图片缓存到本地
    public static void saveViewToImg(Context context, View view) {
//        //打开图像缓存
//        view.setDrawingCacheEnabled(true);
//        //在保存可视组件的截图前，需要先调用measure和layout方法
//        //测量大小
//        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
//                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        //然后就可以把位置和尺寸发送view和所有子view了
//        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//        try{
//            //另一个方法获取可视组件的截图
//            Bitmap bitmap = view.getDrawingCache();
//            //保存截图，位置随意，格式就png吧
//            FileOutputStream outstr = new FileOutputStream("/sdcard/my_certificate.png");
//            //100指压缩率
//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outstr);
//        }catch(Exception e) {
//            e.printStackTrace();
//        }
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        if (Build.VERSION.SDK_INT >= 11) {
            view.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.EXACTLY));
            view.layout((int) view.getX(), (int) view.getY(), (int) view.getX() + view.getMeasuredWidth(), (int) view.getY() + view.getMeasuredHeight());
        } else {
            view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        }
        view.draw(canvas);
        FileOutputStream outstr = null;
        try {
//            File directory_pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            outstr = new FileOutputStream("/sdcard/Pictures/my_certificate.jpg");
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outstr);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File("/sdcard/Pictures/my_certificate.jpg"));
        intent.setData(uri);
        context.sendBroadcast(intent); // 发送广播通知相册
    }

    //多参数传入页面
    public static String targetIdMultiFormat(Map<String, String> map) {
        if (map != null && (map.get("target") != null)) {
            switch (map.get("target")) {
                case "buyerDealerOrderRefundDetail":
                case "orderRefundDetail":// order_id，order_product_id
                    String order_product_id = map.get("order_product_id");
                    String order_id = map.get("order_id");
                    return (order_id == null ? "" : order_id) + "," + (order_product_id == null ? "" : order_product_id);
            }
            return map.get("target_id");
        } else {
            return "";
        }

    }

    //sources 神策埋点 点击商品包含 source_page,source_module,source_element,source_position
    public static void goNewAnyWhere(Context mContext, List<String> targetPlaform, String targetMessage, String target, String target_id, String share_image, String title, String ad_id, String... sources) {
        if (targetPlaform != null && targetPlaform.size() > 0) {
            if (!targetPlaform.contains("android")) {
                if (targetMessage != null) {
                    ToastUtil.showToast(targetMessage);
                }
                return;
            }
        }
        goAnyWhere(mContext, target, target_id, share_image, title, ad_id, sources);
    }

    //sources 神策埋点 点击商品包含 source_page,source_module,source_element,source_position
    public static void goAnyWhere(Context mContext, String target, String target_id, String share_image, String title, String ad_id, String... sources) {
        switch (target) {
            case "product":
                startActivitryWithBundle(mContext, NewCommodityDetailActivity.class, new String[][]{{"id", target_id}, {"ad_id", ad_id}
                        , {"ad_name", title}, {"source_page", sources.length > 0 ? sources[0] : ""}, {"source_module", sources.length > 1 ? sources[1] : ""},
                        {"source_element", sources.length > 2 ? sources[2] : ""}, {"source_position", sources.length > 3 ? sources[3] : ""}});
                break;
            case "orderDetail":
                ARouter.getInstance().build(AroutePath.ORDER_DETAIL_ACTIVITY).withString("order_no", target_id).navigation();
                break;
            case "orderRefundDetail":
                String[] targetIds = target_id.split(",");
                ARouter.getInstance().build(AroutePath.AFTERSALE_DETAIL_ACTIVITY).withString("product_id", targetIds.length > 1 ? targetIds[1] : "")
                        .withString("order_id", targetIds.length > 0 ? targetIds[0] : "").navigation();
                break;
            case "buyerDealerOrderRefundDetail"://经销商买家售后详情
                String[] targetDealerIds = target_id.split(",");
                ARouter.getInstance().build(AroutePath.AFTER_SALE_PURCHASE_DETAIL_ACTIVITY).withString("order_product_id", targetDealerIds.length > 1 ? targetDealerIds[1] : "")
                        .withString("order_id", targetDealerIds.length > 0 ? targetDealerIds[0] : "").navigation();
                break;
            case "sellerDealerOrderRefundDetail"://经销商卖家售后详情
                com.eoner.baselibrary.base.FragmentHostActivity.openFragment(mContext,
                        (Fragment) ARouter.getInstance().build(AroutePath.REFUND_DETAILS_FRAGMENT)
                                .withString("refundNo", target_id)
                                .navigation());
                break;
            case "dealerOrderDetail"://经销商订单详情
                ARouter.getInstance().build(AroutePath.ORDER_DETAIL_ACTIVITY)
                        .withString("order_no", target_id)
                        .withString("from_type", "purchase")
                        .navigation();
                break;
            case "all":
                FragmentHostActivity.openFragment(mContext, (Fragment) ARouter.getInstance().build(AroutePath.CATEGORY_FRAGMENT).navigation());
                break;
            case "seller":
            case "store":
                ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", target_id).navigation();
                break;
            case "index":
                startActivitryWithBundle(mContext, MainActivity.class, new String[][]{{"position", "0"}});
            case "vip_center":
                if (UtilActivity.isCurActivity("MainActivity")) {
                    MainActivity activity = (MainActivity) UtilActivity.getActivity(0);
                    VipCenterFragment personalFragment = new VipCenterFragment();
                    Bundle bundle = new Bundle();
                    personalFragment.setArguments(bundle);
                    activity.setRadioChecked(1);
                    activity.switchContent(activity.currentFragment, personalFragment, 1);
                    UtilActivity.onlyFirst();
                } else {
                    startActivitryWithBundle(mContext, MainActivity.class, new String[][]{{"position", "1"}});
                }
                break;
            case "category":
                startActivitryWithBundle(mContext, CategoryDetailActivity.class, new String[][]{{"from", "firstpage"}, {"cid", target_id}, {"title", title}, {"image", share_image}});
                break;
            case "integral":
                startActivitryWithBundle(mContext, PointProductsActivity.class, new String[][]{{"from", "firstpage"}, {"cid", target_id}, {"title", title}, {"image", share_image}});
                break;
            case "agent":
                MainActivity activity = (MainActivity) UtilActivity.getActivity(0);
                PersonalFragment personalFragment = PersonalFragment.newInstance();
                Bundle bundle = new Bundle();
                bundle.putInt("isOpenAgent", 1);
                personalFragment.setArguments(bundle);
                activity.setRadioChecked(3);
                activity.switchContent(activity.currentFragment, personalFragment, 3);
                UtilActivity.onlyFirst();
                break;
            case "coupon":
                startActivitryWithBundle(mContext, CouponActivity.class, null);
                break;
            case "integral_home":
                startActivitryWithBundle(mContext, PointActivity.class, null);
                break;
            case "gongzhubi_home":
                startActivitryWithBundle(mContext, RedPackedActivity.class, null);
                break;
            case "orderList":
                startActivitryWithBundle(mContext, CustomerOrderActivity.class, new String[][]{{"position", target_id}});
                break;
            case "dealer_bench":
                //经销商工作台
                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.DEALER_BENCH_FRAGMENT)
                            .navigation();
                    FragmentHostActivity.openFragment(mContext, fragment);
                } else {
                    startActivitryWithBundle(mContext, QuickLoginActivity.class, null);
                }
                break;
            case "sale_order"://销售订单
                ARouter.getInstance().build(AroutePath.DEALER_SALE_ORDERS_ACTIVITY)
                        .withInt("position", 0).navigation();
                break;
            case "purchase"://我要采购
                ARouter.getInstance().build(AroutePath.PURCHASE_ACTIVITY).navigation();
                break;
            case "dealer_goods_manage"://经销商商品管理
                ARouter.getInstance().build(AroutePath.DEALER_PRODUCT_MANAGER_ACTIVITY).navigation();
                break;
            case "purchase_manage"://采购单管理
                ARouter.getInstance().build(AroutePath.PURCHASE_ORDERS_ACTIVITY)
                        .withInt("position", 0)
                        .withString("from_type", "purchase").navigation();
                break;
            case "pick_goods"://我的提货单
                ARouter.getInstance().build(AroutePath.PICK_GOODS_ACTIVITY)
                        .withInt("position", TextUtils.isEmpty(target_id) ? 0 : Integer.parseInt(target_id))
                        .navigation();
                break;
            case "dealer_income":
                //经销商---我的收入
                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.ACCUMULATED_INCOME_FRAGMENT)
                            .navigation();
                    FragmentHostActivity.openFragment(mContext, fragment);
                } else {
                    startActivitryWithBundle(mContext, QuickLoginActivity.class, null);
                }
                break;
            case "member_income":
                //会员——我的收入
                startActivitryWithBundle(mContext, InComeActivity.class, null);
                break;
            case "member_commission":
                //会员——推广收益
                startActivitryWithBundle(mContext, PromotionProfitActivity.class, null);
                break;
            case "member_sale_detail":
                //会员——零售单详情
                startActivitryWithBundle(mContext, SaleOrderDetailActivity.class,
                        new String[][]{{"order_no", target_id}});
                break;
            case "trackOrder_1":
            case "trackOrder_2":
                //物流详情
                Bundle bundleTrack = new Bundle();
                bundleTrack.putString("order_id", target_id);
                bundleTrack.putString("track_no", "");
                bundleTrack.putString("biz_type", target.equals("trackOrder_1") ? "1" : "2");
                bundleTrack.putBoolean("showKefu", false);
                Intent intent = new Intent(mContext, LogistInfoActivity.class);
                intent.putExtras(bundleTrack);
                mContext.startActivity(intent);
                break;
            default:
                if (target.startsWith("http")) {
                    if (target.startsWith("http://news")) {
                        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.MEET_REPORT_FRAGMENT)
                                .withString("page_name", "news")
                                .navigation();
                        FragmentHostActivity.openFragment(mContext, fragment);
                    } else if (target.startsWith("http://view")) {
                        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.MEET_REPORT_FRAGMENT)
                                .withString("page_name", "views")
                                .navigation();
                        FragmentHostActivity.openFragment(mContext, fragment);
                    } else if (target.startsWith("http://history")) {
                        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.MEET_REPORT_FRAGMENT)
                                .withString("page_name", "historys")
                                .navigation();
                        FragmentHostActivity.openFragment(mContext, fragment);
                    } else if (target.startsWith("http://master")) {
                        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.MASTER_MIEN_FRAGMENT)
                                .withString("page_name", "history")
                                .navigation();
                        FragmentHostActivity.openFragment(mContext, fragment);
                    } else {
                        if (target.contains("platformType") && target.contains("platformCode")) {
                            startActivitryWithBundle(mContext, CzbWebActivity.class, new String[][]{{"url", target}});
                        } else {
                            startActivitryWithBundle(mContext, BridgeActivity.class, new String[][]{{"url", target}, {"share_image", share_image}, {"title", title}});
                        }
                    }
                }
                break;
        }
    }


    public static void goAnyWhereBundle(Context mContext, Map<String, String> map) {
        String target = map.get("target");
        String target_id = map.get("target_id");
        String code = map.get("code");
        switch (target) {
            case "product":
                startActivitryWithBundle(mContext, NewCommodityDetailActivity.class,
                        new String[][]{{"id", target_id}, {"qrcode", code}});
                break;
            case "all":
                FragmentHostActivity.openFragment(mContext, (Fragment) ARouter.getInstance().build(AroutePath.CATEGORY_FRAGMENT).navigation());
                break;
            case "seller":
            case "store":
                ARouter.getInstance().build(AroutePath.STORE_ACTIVITY)
                        .withString("store_id", target_id).withString("qrcode", code).navigation();
                break;
            case "index":
                startActivitryWithBundle(mContext, MainActivity.class,
                        new String[][]{{"position", "0"}, {"qrcode", code}});
                break;
            case "vip_center":
                startActivitryWithBundle(mContext, MainActivity.class, new String[][]{{"position", "1"}});
                break;
            case "category":
                startActivitryWithBundle(mContext, CategoryDetailActivity.class,
                        new String[][]{{"from", "firstpage"}, {"cid", target_id}, {"qrcode", code}});
                break;
            case "integral":
                startActivitryWithBundle(mContext, PointProductsActivity.class,
                        new String[][]{{"from", "firstpage"}, {"cid", target_id}, {"qrcode", code}});
                break;
            case "coupon":
                startActivitryWithBundle(mContext, CouponActivity.class, new String[][]{{"qrcode", code}});
                break;
            case "integral_home":
                startActivitryWithBundle(mContext, PointActivity.class, new String[][]{{"qrcode", code}});
                break;
            case "gongzhubi_home":
                startActivitryWithBundle(mContext, RedPackedActivity.class, new String[][]{{"qrcode", code}});
                break;
            case "orderList":
                startActivitryWithBundle(mContext, CustomerOrderActivity.class, new String[][]{{"position", target_id}, {"qrcode", code}});
                break;
            case "dealer_bench":
                //经销商工作台
                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.DEALER_BENCH_FRAGMENT)
                            .navigation();
                    FragmentHostActivity.openFragment(mContext, fragment);
                } else {
                    startActivitryWithBundle(mContext, QuickLoginActivity.class, null);
                }
                break;
            case "sale_order"://销售订单
                ARouter.getInstance().build(AroutePath.DEALER_SALE_ORDERS_ACTIVITY)
                        .withInt("position", 0).navigation();
                break;
            case "purchase"://我要采购
                ARouter.getInstance().build(AroutePath.PURCHASE_ACTIVITY).navigation();
                break;
            case "dealer_goods_manage"://经销商商品管理
                ARouter.getInstance().build(AroutePath.DEALER_PRODUCT_MANAGER_ACTIVITY).navigation();
                break;
            case "purchase_manage"://采购单管理
                ARouter.getInstance().build(AroutePath.PURCHASE_ORDERS_ACTIVITY)
                        .withInt("position", 0)
                        .withString("from_type", "purchase").navigation();
                break;
            case "pick_goods"://我的提货单
                ARouter.getInstance().build(AroutePath.PICK_GOODS_ACTIVITY)
                        .withInt("position", TextUtils.isEmpty(target_id) ? 0 : Integer.parseInt(target_id))
                        .navigation();
                break;
            case "dealer_income":
                //经销商---我的收入
                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.ACCUMULATED_INCOME_FRAGMENT)
                            .navigation();
                    FragmentHostActivity.openFragment(mContext, fragment);
                } else {
                    startActivitryWithBundle(mContext, QuickLoginActivity.class, null);
                }
                break;
            default:
                if (target.startsWith("http")) {
                    if (target.contains("platformType") && target.contains("platformCode")) {
                        startActivitryWithBundle(mContext, CzbWebActivity.class,
                                new String[][]{{"url", target}, {"qrcode", code}});
                    } else {
                        startActivitryWithBundle(mContext, BridgeActivity.class,
                                new String[][]{{"url", target}, {"qrcode", code}});
                    }

                }
                break;
        }
    }

    public static void startActivitryWithBundle(Context mContext, @NonNull Class clazz, String[][] val) {
        Intent intent = new Intent(mContext, clazz);
        Bundle bundle = new Bundle();
        if (val != null) {
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        mContext.startActivity(intent);
    }

    public static void copy(Context context, String str) {
        if (!TextUtils.isEmpty(str)) {
            ClipboardManager myClipboard = (ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
            ClipData myClip = ClipData.newPlainText("text", str);
            myClipboard.setPrimaryClip(myClip);
            ToastUtil.showToast("复制成功");
        }
    }

    public static String getLevetText(int level) {
        if (1 == level)
            return "注册会员";
        else if (2 == level)
            return "贵宾";
        else if (3 == level)
            return "银卡会员";
        else if (4 == level)
            return "金卡会员";
        else if (5 == level)
            return "黑卡代理";
        else if (6 == level)
            return "经销商";
        else if (7 == level)
            return "服务商";
        else if (8 == level)
            return "合伙人";
        return "";
    }

    public static boolean isXStart(String str) {
        return str.startsWith("X-");
    }

    public static boolean isHStart(String str) {
        return str.startsWith("H-");
    }

    public static void openUrl(Context context, String url) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast("未安装葵花子APP，请安装后重试");
        }
    }

    /**
     * 打开第三方app
     *
     * @param content
     * @param packageName
     */
    public static boolean startApp(Context content, String packageName) {
        Intent intent = openIntentByPackageName(content, packageName);
        if (null == intent) {
            return false;
        }
        content.startActivity(intent);
        return true;
    }

    public static Intent openIntentByPackageName(Context context, String packageName) {
        String activityName = null;
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        @SuppressLint("WrongConstant") List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                activityName = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(activityName)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, activityName));
        return intent;
    }
}
